package com.lizard.schedule.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.lizard.schedule.ScheduleApplication;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.List;

/**
 * Schedule app工具类
 */
public class ScheduleUtil {

    /**
     * 包名
     */
    private static String packageName;

    /**
     * 版本号
     */
    private static int versionCode;

    /**
     * 版本名称
     */
    private static String versionName;

    /**
     * 是否处于调试模式
     */
    private static boolean debuggable;


    /**
     * 用于应用启动初始化
     */
    public static void init(){
        packageName = ScheduleApplication.applicationContext.getPackageName();
        try {
            PackageInfo schedulePackageInfo = ScheduleApplication.applicationContext.getPackageManager().getPackageInfo(packageName, 0);
            versionCode = schedulePackageInfo.versionCode;
            versionName = schedulePackageInfo.versionName;
            ScheduleApplication.applicationContext.getApplicationInfo();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        ApplicationInfo scheduleApplicationInfo = ScheduleApplication.applicationContext.getApplicationInfo();
        debuggable = ((scheduleApplicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE)!=0);
    }

    /**
     * 获取版本名称
     *
     * @return
     */
    public static String getVersionName(){
        return versionName;
    }

    /**
     * 获取版本号
     *
     * @return
     */
    public static int getVersionCode(){
        return versionCode;
    }

    /**
     * 获取包名
     *
     * @return
     */
    public static String getPackageName(){
        return packageName;
    }

    /**
     * 是否调试模式
     *
     * @return
     */
    public static boolean isDebuggable(){
        return  debuggable;
    }

    /**
     * 获取进程名称
     *
     * @param pID
     * @return
     */
    public static String getAppProcessName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) ScheduleApplication.applicationContext.getSystemService(Context.ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = ScheduleApplication.applicationContext.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
            }
        }
        return processName;
    }

    /**
     * 转换为小红点里面应该显示的数值
     *
     * @param count 大于0的整数
     * @return
     */
    public static String transferCountInRedPoint(int count){
        return count > 99 ? "99+" : count + "";
    }

    /**
     * 实现文本复制功能
     * @param content
     */
    public static void copy(String content) {
        // 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) ScheduleApplication.applicationContext
                .getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content.trim());
    }

    /**
     * 实现粘贴功能
     *
     * @return
     */
    public static String paste() {
        // 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) ScheduleApplication.applicationContext
                .getSystemService(Context.CLIPBOARD_SERVICE);
        return cmb.getText().toString().trim();
    }

    /**
     * 获取AndroidManifest中的meta-data值
     *
     * @param metaDataName
     * @return
     */
    public static String getMetaDataValue(String metaDataName){
        String value = null;
        try {
            ApplicationInfo appInfo = ScheduleApplication.applicationContext.getPackageManager()
                    .getApplicationInfo(ScheduleApplication.applicationContext.getPackageName(),PackageManager.GET_META_DATA);
            if(appInfo != null){
                Bundle bundle = appInfo.metaData;
                if(bundle != null){
                    Object mChannelObj = bundle.get(metaDataName);
                    if(mChannelObj != null){
                        value = String.valueOf(mChannelObj);
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 获取应用指纹签名MD5值
     *
     * @return
     */
    public static String getAppMd5FingerPrint(){
        //获取包管理器
        PackageManager pm = ScheduleApplication.applicationContext.getPackageManager();
        //获取当前要获取SHA1值的包名，也可以用其他的包名，但需要注意，
        //在用其他包名的前提是，此方法传递的参数Context应该是对应包的上下文。
        String packageName = ScheduleApplication.applicationContext.getPackageName();
        //返回包括在包中的签名信息
        int flags = PackageManager.GET_SIGNATURES;
        PackageInfo packageInfo = null;
        try {
            //获得包的所有内容信息类
            packageInfo = pm.getPackageInfo(packageName, flags);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        //签名信息
        Signature[] signatures = packageInfo.signatures;
        byte[] cert = signatures[0].toByteArray();
        //将签名转换为字节数组流
        InputStream input = new ByteArrayInputStream(cert);
        //证书工厂类，这个类实现了出厂合格证算法的功能
        CertificateFactory cf = null;
        try {
            cf = CertificateFactory.getInstance("X509");
        } catch (CertificateException e) {
            e.printStackTrace();
        }
        //X509证书，X.509是一种非常通用的证书格式
        X509Certificate c = null;
        try {
            c = (X509Certificate) cf.generateCertificate(input);
        } catch (CertificateException e) {
            e.printStackTrace();
        }
        String hexString = null;
        try {
            //加密算法的类，这里的参数可以使MD4,MD5等加密算法
            MessageDigest md = MessageDigest.getInstance("MD5");
            //获得公钥
            byte[] publicKey = md.digest(c.getEncoded());
            //字节到十六进制的格式转换
            hexString = byte2HexFormatted(publicKey);
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (CertificateEncodingException e) {
            e.printStackTrace();
        }
        return hexString;
    }

    /**
     * 字节转换为16进制加密内容字符串
     *
     * @param arr
     * @return
     */
    private static String byte2HexFormatted(byte[] arr) {
        StringBuilder str = new StringBuilder(arr.length * 2);
        for (int i = 0; i < arr.length; i++) {
            String h = Integer.toHexString(arr[i]);
            int l = h.length();
            if (l == 1)
                h = "0" + h;
            if (l > 2)
                h = h.substring(l - 2, l);
            str.append(h);
        }
        return str.toString();
    }

    /**
     * 将二进制转换成16进值制 ，防止byte[]数字转换成string类型时造成的数据损失
     *
     * @param buf
     * @return 返回16进制转换成的string
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();

    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr 16进制的数组转换成String类型再传过来的参数
     * @return 转换回来的二进制数组
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 关闭软键盘
     *
     * @param activity
     */
    public static void hideSoftInput(Activity activity){
        if (activity.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (activity.getCurrentFocus() != null){
                InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),InputMethodManager.RESULT_UNCHANGED_SHOWN);
            }
        }
    }

    /**
     * 强制打开软键盘
     *
     * @param context
     * @param view
     */
    public static void showSoftInput(Context context, View view){
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

}
